package assign4;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

/** Common functions for setting up security policies
 */
public class Policy
{
	public static final String POLICY_FILE_NAME = Globals.policyFileLocation;

	@SuppressWarnings("unchecked")
	public static void init(Class classToAdd)
	{
		System.setProperty("java.rmi.server.codebase", classToAdd.getProtectionDomain().getCodeSource().getLocation().toString());
		System.setProperty("java.security.policy", Policy.getPath());
		if (System.getSecurityManager() == null)
		{
			System.setSecurityManager(new SecurityManager());
		}
	}

	private static String getPath()
	{
		try
		{
			File tempFile = File.createTempFile("rmi-base", ".policy");
			InputStream is = DBServerCreator.class.getResourceAsStream(POLICY_FILE_NAME);
			BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
			int read = 0;
			while ((read = is.read()) != -1)
			{
				writer.write(read);
			}
			writer.close();
			tempFile.deleteOnExit();
			return tempFile.getAbsolutePath();
		}
		catch (IOException e)
		{
			throw new RuntimeException(e);
		}
	}
}